package com.example.gokuplayalong.service.fragments.users.receive;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.alipay.directpay.DirectPay;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.threadpool.CustomThreadPoolExecutor;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.huawei.hms.ads.App;
import com.kongzue.dialogx.dialogs.PopTip;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserMainReceiveOrderDetail#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class UserMainReceiveOrderDetail extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    View rootView;
    private ImageView mUserMainReceiveOrderDetailIv;
    private ImageView mUserMainReceiveOrderDetailHeadshot;
    private TextView mUserMainReceiveOrderDetailMerchantName;
    private TextView mUserMainReceiveOrderDetailMerchantDesc;
    private TextView mUserMainReceiveOrderDetailMerchantScore;
    private TextView mUserMainReceiveOrderDetailMerchantGuide;
    private TextView mUserMainReceiveOrderDetailGameType;
    private TextView mUserMainReceiveOrderDetailTimes;
    private TextView mUserMainReceiveOrderDetailStartTime;
    private TextView mUserMainReceiveOrderDetailOrdernum;
    private TextView mUserMainReceiveOrderDetailOriginBalance;
    private TextView mUserMainReceiveOrderDetailCouponsBalance;
    private TextView mUserMainReceiveOrderDetailOrderBalance;
    private CheckBox mUserMainReceiveOrderDetailWayAlipay;
    private CheckBox mUserMainReceiveOrderDetailWayWeixin;
    private Button mUserMainReceiveOrderDetailPay;

    JSONObject merchantInfo = new JSONObject();
    JSONObject serviceType = new JSONObject();

    JSONArray skillsList = new JSONArray();

    double originBalance = 0;
    double orderBalance = 0;
    double couponsBalance = 0;

    Beans bean = new Beans();
    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    try {
                        Bundle bundle = msg.getData();
                        bean.setJsonObject(JSON.parseObject(bundle.getString("bean")));
                        UIRefresh();
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
            }
        }
    };


    public UserMainReceiveOrderDetail() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserMainReceiveOrderDetail.
     */
    // TODO: Rename and change types and number of parameters
    public static UserMainReceiveOrderDetail newInstance(String param1, String param2) {
        UserMainReceiveOrderDetail fragment = new UserMainReceiveOrderDetail();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_user_main_receive_order_detail, container, false);
        initView();
        return rootView;
    }

    private void initView() {


        mUserMainReceiveOrderDetailIv = rootView.findViewById(R.id.user_main_receive_order_detail_iv);
        mUserMainReceiveOrderDetailHeadshot = rootView.findViewById(R.id.user_main_receive_order_detail_headshot);
        mUserMainReceiveOrderDetailMerchantName = rootView.findViewById(R.id.user_main_receive_order_detail_merchant_name);
        mUserMainReceiveOrderDetailMerchantDesc = rootView.findViewById(R.id.user_main_receive_order_detail_merchant_desc);
        mUserMainReceiveOrderDetailMerchantScore = rootView.findViewById(R.id.user_main_receive_order_detail_merchant_score);
        mUserMainReceiveOrderDetailMerchantGuide = rootView.findViewById(R.id.user_main_receive_order_detail_merchant_guide);
        mUserMainReceiveOrderDetailGameType = rootView.findViewById(R.id.user_main_receive_order_detail_game_type);
        mUserMainReceiveOrderDetailTimes = rootView.findViewById(R.id.user_main_receive_order_detail_times);
        mUserMainReceiveOrderDetailStartTime = rootView.findViewById(R.id.user_main_receive_order_detail_start_time);
        mUserMainReceiveOrderDetailOrdernum = rootView.findViewById(R.id.user_main_receive_order_detail_ordernum);
        mUserMainReceiveOrderDetailOriginBalance = rootView.findViewById(R.id.user_main_receive_order_detail_origin_balance);
        mUserMainReceiveOrderDetailCouponsBalance = rootView.findViewById(R.id.user_main_receive_order_detail_coupons_balance);
        mUserMainReceiveOrderDetailOrderBalance = rootView.findViewById(R.id.user_main_receive_order_detail_order_balance);
        mUserMainReceiveOrderDetailWayAlipay = rootView.findViewById(R.id.user_main_receive_order_detail_way_alipay);
        mUserMainReceiveOrderDetailWayWeixin = rootView.findViewById(R.id.user_main_receive_order_detail_way_weixin);
        mUserMainReceiveOrderDetailPay = rootView.findViewById(R.id.user_main_receive_order_detail_pay);

        mUserMainReceiveOrderDetailPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;


                    Beans beansIn = new Beans();
                    beansIn.getJsonObject()
                            .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                                    .getString("phone"));
                    beansIn.getJsonObject().put("subject", "悟空陪玩下单");
                    beansIn.getJsonObject().put("total_amount", orderBalance);
                    beansIn.getJsonObject()
                            .put("merchant_id", merchantInfo.getString("merchantid"));

                    AppParams.getNewNetWork()
                            .setInterface(new NetWorkInterface() {
                                @Override
                                public int success(String msg) {
                                    try {
                                        JSONObject msgFromServer = JSON.parseObject(msg);
                                        if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                            DirectPay.getNewDirectPay()
                                                    .payV2(msgFromServer.getString("orderInfo"), beansIn);
                                        }
                                    } catch (Throwable e) {
                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                    }
                                    return 0;
                                }

                                @Override
                                public int failed(String msg) {
                                    return 0;
                                }
                            })
                            .execute(AppParams.getInstance().baseUrl + "/buildOrderInfo", beansIn.getJsonObject()
                                    .toJSONString());

                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainReceiveOrderDetailIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchBackOnSysFragment();
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
    }

    private void initChanged() {
        try {


        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }


    private void UIRefresh() {

        try {
            merchantInfo = JSON.parseObject(bean.getJsonObject().getString("merchantInfo"));
            skillsList = JSON.parseArray(bean.getJsonObject().getString("skillsList"));
            serviceType = JSON.parseObject(merchantInfo.getString("servicetype"));


            JSONObject orderData = JSON.parseObject(bean.getJsonObject().getString("orderData"));

            if (orderData != null && !orderData.isEmpty()) {

                originBalance = Integer.parseInt(orderData.getString("serviceTimes")) * serviceType.getDoubleValue(orderData.getString("serviceType"));
                orderBalance = originBalance + couponsBalance;


                mUserMainReceiveOrderDetailGameType.setText(orderData.getString("gameType"));
                mUserMainReceiveOrderDetailStartTime.setText(String.format("%s月%s日 %s:%s", orderData.getString("month"), orderData.getString("day"), orderData.getString("startTimeHour"), orderData.getString("startTimeMinute")));
                mUserMainReceiveOrderDetailTimes.setText(String.format("%s小时", orderData.getString("serviceTimes")));

                mUserMainReceiveOrderDetailOrdernum.setText(orderData.getString("ordernum"));
                mUserMainReceiveOrderDetailOriginBalance.setText(String.format("¥%s", Tools.doubleFormat(originBalance)));
                mUserMainReceiveOrderDetailCouponsBalance.setText(String.format("¥%s", Tools.doubleFormat(couponsBalance)));
                mUserMainReceiveOrderDetailOrderBalance.setText(String.format("¥%s", Tools.doubleFormat(orderBalance)));

            }


        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }

        try {


            String filename = merchantInfo.getString("phone") + "_merchant_headshot_upload.png";
            Picasso.with(MainActivity.getInstance())
                    .load(AppParams.getInstance().uploadMediaLocationServer + "/" + filename)
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .networkPolicy(NetworkPolicy.NO_CACHE)
                    .into(mUserMainReceiveOrderDetailHeadshot);

            JSONObject data = JSON.parseObject(merchantInfo.getString("data"));
            if (data != null) {

                if (!StringUtils.isEmpty(data.getDoubleValue("merchantScore") + "")) {
                    mUserMainReceiveOrderDetailMerchantScore.setText(String.format("%s分", data.getDoubleValue("merchantScore")));
                }
                else {
                    mUserMainReceiveOrderDetailMerchantScore.setText("0.0分");
                }
                if (!StringUtils.isEmpty(data.getString("merchantName"))) {
                    mUserMainReceiveOrderDetailMerchantName.setText(data.getString("merchantName"));
                }
                else {
                    if (Objects.equals(data.getString("bodyType"), "企业") || Objects.equals(data.getString("bodyType"), "个体工商户")) {
                        mUserMainReceiveOrderDetailMerchantName.setText(data.getString("companiesMerchantAbbreviation"));
                    }
                    else if (Objects.equals(data.getString("bodyType"), "个人")) {
                        mUserMainReceiveOrderDetailMerchantName.setText(data.getString("individualMerchantAbbreviation"));
                    }
                }
                if (!StringUtils.isEmpty(data.getString("merchantManifesto"))) {
                    mUserMainReceiveOrderDetailMerchantDesc.setText(data.getString("merchantManifesto"));
                }
            }
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}